from fastapi import APIRouter, Depends, Body

from odoo.api import Environment
from odoo.addons.fastapi.dependencies import odoo_env

from odoo.addons.fastapi_odoo_bridge.core.exception import BusinessException, CustomResponse
from odoo.addons.fastapi_odoo_bridge.core.response import custom_response
from ..basemodels.fir_level import TranslationLine, TranslationTable, TranslationProgram, TranslationClient

from odoo.addons.rp_international_management.functions.rp_translation_table_fc import RPTranslationTableFC

from .common_rt import get_program_and_client

router = APIRouter(prefix='/android', tags=['Android 调用方式'])


@router.post('/batch_upload',
             response_model=CustomResponse[dict],
             summary='批量上传多语言记录',
             description='批量上传，如果没有则创建，如果有则更新。需要注意的是，如果android请严格遵照索引中‘.’替换为‘1’的规则进行操作', )
@custom_response
async def batch_upload(table: TranslationTable = Body(..., description='项目'),
                       env: Environment = Depends(odoo_env)):
    # 1、获取项目、终端
    program, client = get_program_and_client(env, table.program, table.client)
    # 2、遍历line,创建或者更新翻译对照表
    for line in table.line:
        # android做单独处理，将“fir1sec1trd”转换成“fir.sec.trd”
        index = line.index.replace("1", ".")
        RPTranslationTableFC(env).update_table(program, client, index, line.chinese, line.english, line.spanish, line.catalan)

    return {'result': 'OK'}


@router.post('/batch_download',
             response_model=CustomResponse[TranslationTable],
             summary='批量获取多语言记录',
             description='批量获取多语言记录')
@custom_response
async def batch_download(table: TranslationTable = Body(..., description='项目'),
                         env: Environment = Depends(odoo_env)):
    program, client = get_program_and_client(env, table.program, table.client)

    table_line = env['rp.translation.table'].search([('program_id', '=', program.id), ('client_id', '=', client.id)])

    # android做单独处理，将“fir.sec.trd”转换成“fir1sec1trd”
    line_items = [TranslationLine(index=line['index_id']['code'].replace(".", "1") if line['index_id']['code'] is not False else None,
                                  chinese=line['chinese'] if line['chinese'] is not False else None,
                                  english=line['english'] if line['english'] is not False else None,
                                  spanish=line['spanish'] if line['spanish'] is not False else None,
                                  catalan=line['catalan'] if line['catalan'] is not False else None) for line in table_line]
    trans_program = TranslationProgram(__from_odoo=program, __env=env)
    trans_client = TranslationClient(__from_odoo=client, __env=env)
    translation_table = TranslationTable(program=trans_program, client=trans_client, line=line_items)

    return translation_table
